import axios from "axios";
import { Toast } from "vant";
import CryptoJS from "crypto-js"; // 改为导入整个CryptoJS
// import  AESEncryptUtil from '@/utils/CryptoJS'
// const baseURL = process.env.VUE_APP_BASE_API
const baseURL = import.meta.env.VITE_API_URL;
export const BaseUrl = baseURL;
// export const BaseUrl = "http://192.168.1.103:9948/";
// create an axios instance
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL,
  timeout: 30000, // request timeout
});
const AESEncryptUtil = {
  ioskey: [49, 113, 97, 122, 64, 87, 83, 88, 41, 79, 75, 77, 57, 105, 106, 110],
  iosiv: [
    122, 120, 99, 118, 47, 46, 44, 109, 94, 84, 70, 67, 55, 121, 103, 118,
  ],
  get key() {
    return String.fromCharCode(...this.ioskey);
  },

  get iv() {
    return String.fromCharCode(...this.iosiv);
  },
  encrypt: function (plainText) {
    const base64Str = this.base64Encode(plainText);
    return Promise.resolve(this.aesEncrypt(base64Str));
  },

  base64Encode: function (str) {
    return btoa(unescape(encodeURIComponent(str)));
  },

  aesEncrypt: function (data) {
    try {
      const key = CryptoJS.enc.Utf8.parse(this.key);
      const iv = CryptoJS.enc.Utf8.parse(this.iv);

      const encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      });

      return encrypted.ciphertext.toString(CryptoJS.enc.Hex);
    } catch (error) {
      console.error("AES加密失败:", error);
      throw error;
    }
  },
};
const appKeyByte = [
  163, 171, 106, 219, 132, 225, 77, 199, 174, 228, 252, 4, 99, 103, 32, 110,
];
const appKeyString = appKeyByte
  .map((num) => num.toString(16).padStart(2, "0")) // 转换为2位十六进制
  .join("");
const originalStr = `appKey=${appKeyString}$&timestamp=${new Date().getTime()}`;
// 方式1：使用Promise的then
AESEncryptUtil.encrypt(originalStr)
  .then((encrypted) => {
    console.log("加密结果:", encrypted);
    return encrypted;
  })
  .catch((error) => {
    console.error("加密出错:", error);
  });

const setDefaultParam = async (param) => {
  try {
    const appKeyByte = [
      163, 171, 106, 219, 132, 225, 77, 199, 174, 228, 252, 4, 99, 103, 32, 110,
    ];
    const appKeyString = appKeyByte
      .map((num) => num.toString(16).padStart(2, "0")) // 转换为2位十六进制
      .join("");
    console.log(appKeyString, 123456);

    const encrypted = await AESEncryptUtil.encrypt(
      `appKey=${appKeyString}&timestamp=` + new Date().getTime()
      //   originalStr
    );
    console.log(encrypted, 11111);

    // 合并原始参数和加密参数
    return { ...param, params: encrypted };
  } catch (error) {
    console.error("加密失败:", error);
    throw error;
  }
};
service.interceptors.request.use(
  async (config) => {
    // 注意：这里改为 async 函数以支持异步操作
    const { data, params, method } = config;

    try {
      // 根据请求方法类型处理不同参数
      if (method === "get") {
        // GET请求：参数放在URL的params中
        config.params = await setDefaultParam(params || {});
      } else if (method === "put" || method === "post") {
        // PUT/POST请求：参数放在请求体data中
        config.data = await setDefaultParam(data || {});
      }
      return config;
    } catch (error) {
      console.log("请求拦截器处理出错:", error);
      return Promise.reject(error);
    }
  },
  (error) => {
    console.log("请求拦截器异常:", error);
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    console.log("原始响应:", response); // 打印原始响应
    return response.data; // 确保返回 response.data
  },
  (error) => {
    // 判断
    setTimeout(() => {
      Toast("服务器正在开小差~");
    }, 100);
    return Promise.reject(error);
  }
);

export default service;
